package com.ktg.mes.pro.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ktg.common.constant.UserConstants;
import com.ktg.common.core.domain.APIResult;
import com.ktg.common.core.domain.Result;
import com.ktg.common.utils.DateUtils;
import com.ktg.common.utils.StringUtils;
import com.ktg.common.utils.poi.ExcelRowModel;
import com.ktg.common.utils.poi.ExcelTitle;
import com.ktg.common.utils.poi.ExcelUtil2;
import com.ktg.mes.atuoVue.PowerAuthentication;
import com.ktg.mes.atuoVue.QueryParam;
import com.ktg.mes.atuoVue.TableColumn;
import com.ktg.mes.atuoVue.WebModel;
import com.ktg.mes.md.domain.MdItem;
import com.ktg.mes.md.domain.MdProductStatisticsBom;
import com.ktg.mes.md.domain.MesScalesOrderItem;
import com.ktg.mes.md.service.IMdItemService;
import com.ktg.mes.md.service.IMdProductStatisticsBomService;
import com.ktg.mes.md.service.IMesScalesOrderItemService;
import com.ktg.mes.pro.domain.*;
import com.ktg.mes.pro.service.*;
import com.ktg.mes.rec.domain.RecLnspectionRecord;
import com.ktg.mes.rec.service.IRecLnspectionRecordService;
import com.ktg.mes.util.LGLeftJoinQueryWrapper;
import com.ktg.mes.wm.service.IWmItemRecptLineService;
import com.ktg.mes.wm.service.IWmStockOutService;
import com.ktg.system.strategy.AutoCodeUtil;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.ktg.common.annotation.Log;
import com.ktg.common.core.controller.BaseController;
import com.ktg.common.core.domain.AjaxResult;
import com.ktg.common.enums.BusinessType;
import com.ktg.common.utils.poi.ExcelUtil;
import com.ktg.common.core.page.TableDataInfo;

/**
 * 生产任务Controller
 *
 * @author yinjinlu
 * @date 2022-05-14
 */

@RestController
@RequestMapping("/mes/pro/protask")
public class ProTaskController extends BaseController
{
    @Autowired
    private IProTaskService proTaskService;

    @Autowired
    private IProWorkorderService proWorkorderService;

    @Autowired
    private IProProcessService proProcessService;

    @Autowired
    private AutoCodeUtil autoCodeUtil;

    @Autowired
    private IMdItemService mdItemService;

    @Autowired
    private IRecLnspectionRecordService recLnspectionRecordService;


    @Autowired
    private IMesScalesOrderItemService mesScalesOrderItemService;


    @Autowired
    private IWmItemRecptLineService itemRecptLineService;

    @Autowired
    private IWmStockOutService wmStockOutService;

    @Autowired
    private IProTaskChangeVersionService proTaskChangeVersionService;

    @Autowired
    private IMdProductStatisticsBomService productStatisticsBomService;
    private Integer countIndex;


    /**
     * 查询生产任务列表
     */
    @PreAuthorize("@ss.hasPermi('mes:pro:protask:list')")
    @GetMapping("/list")
    public TableDataInfo list(ProTask proTask, HttpServletRequest req)
    {
        startPage();
        Map map = req.getParameterMap();
        LGLeftJoinQueryWrapper<Object> lgLeftJoinQueryWrapper = new LGLeftJoinQueryWrapper<>(proTask,map,proTask.getPage(),proTask.getPageCount());
        lgLeftJoinQueryWrapper.setSelectColumn("*" +
                ",( SELECT COUNT( 0 ) FROM pro_workorder WHERE batch_code = \"batchCode\" ) AS barrelage" +
                ",(SELECT string_agg(remark , ';') FROM wm_stock_will_out WHERE stock_type = 'pro_workorder' and stock_id = \"workorderId\"::VARCHAR) as willOutRemark " +
                "");
        lgLeftJoinQueryWrapper.setDefaultDateFormat("yyyy-MM-dd HH:mm:ss");
        lgLeftJoinQueryWrapper.orderByDesc("batch_no");
        List<JSONObject> list = wmStockOutService.lgListMap(lgLeftJoinQueryWrapper);
//        List<ProTask> list = proTaskService.selectProTaskList(proTask);
        return getDataTable(list);
    }

    /**
     * 导出生产任务列表
     */
    @PreAuthorize("@ss.hasPermi('mes:pro:protask:export')")
    @Log(title = "生产任务", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ProTask proTask)
    {
        List<ProTask> list = proTaskService.selectProTaskList(proTask);
        ExcelUtil<ProTask> util = new ExcelUtil<ProTask>(ProTask.class);
        util.exportExcel(response, list, "生产任务数据");
    }

    /**
     * 获取生产任务详细信息
     */
    @PreAuthorize("@ss.hasPermi('mes:pro:protask:query')")
    @GetMapping(value = "/{taskId}")
    public AjaxResult getInfo(@PathVariable("taskId") String taskId)
    {
        return AjaxResult.success(proTaskService.selectProTaskByTaskId(Long.valueOf(taskId)));
    }


    /**
     * PDA 获取当前任务
     * @param batchNo
     * @return
     */
    @GetMapping("/batchNo")
    public AjaxResult batchNo(@RequestParam(value = "batchNo",required = false) String batchNo){
        QueryWrapper<ProTask> queryWrapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(batchNo)){
            queryWrapper.eq("batch_no",batchNo);
            queryWrapper.last("limit 1");
        }else {
            //查询排产在这前两天，今天和明天数据
            queryWrapper.between("production_date", DateUtils.getDatetimeByAdd(-30),DateUtils.getDatetimeByAdd(1));
            //查询未完成任务
            queryWrapper.isNull("end_time");
        }
        queryWrapper.orderByDesc("production_date");

        List<ProTask> tasks = proTaskService.list(queryWrapper);
        return AjaxResult.success(tasks);

    }


    /**
     * 获取甘特图中需要显示的TASK，包括三种类型的内容：
     * 1.Project：基于时间范围搜索的生产工单转换而来的Project。
     *   搜索逻辑为：默认使用当前日期作为开始时间，搜索所有需求时间大于当前时间的生产工单
     * 2.Task：基于生产工单拆分到具体工作站后的生产任务转换而来的Task。
     * 3.Link：根据工序与工序之间的依赖关系转换而来的Link。
     */
    @PreAuthorize("@ss.hasPermi('mes:pro:protask:list')")
    @GetMapping("/listGanttTaskList")
    public AjaxResult getGanttTaskList(ProWorkorder proWorkorder){
        GanttTask ganttTask = new GanttTask();
        List<GanttData> ganttData = new ArrayList<GanttData>();
        List<GanttLink> ganttLinks = new ArrayList<GanttLink>();

        //查询所有的WorkOrder
        List<ProWorkorder> workorders = proWorkorderService.selectProWorkorderList(proWorkorder);

        //为每个workOrder生成type=project的GanttData
        //为每个proTask生产type=task的GanttData
        ProTask param = new ProTask();
        if(CollUtil.isNotEmpty(workorders)){
            for (ProWorkorder workorder: workorders) {
                //先添加当前的生产工单TASK
                GanttData wdata = new GanttData();
                wdata.setId("MO"+workorder.getWorkorderId().toString());
                wdata.setText(new StringBuilder().append(workorder.getProductName()).append(workorder.getQuantity().stripTrailingZeros().toPlainString()).append(workorder.getUnitOfMeasure()).toString());//默认使用“[产品]+[数量]+[单位]”格式。
                wdata.setProduct(workorder.getProductName());
                wdata.setQuantity(workorder.getQuantity());
                if(workorder.getParentId().longValue()!=0L){
                    wdata.setParent("MO"+workorder.getParentId().toString());
                }
                wdata.setProgress(0f);
                wdata.setDuration(0L);
                wdata.setType(UserConstants.GANTT_TASK_TYPE_PROJECT);
                ganttData.add(wdata);

                //查询当前生产工单下所有的生产任务
                param.setWorkorderId(workorder.getWorkorderId());
                List<ProTask> proTasks = proTaskService.selectProTaskList(param);
                if(CollUtil.isNotEmpty(proTasks)){
                    for (ProTask task:proTasks) {
                        GanttData data = new GanttData();
                        data.setId(task.getTaskId().toString());//使用生产任务的ID作为甘特图TASK的ID
                        data.setText(new StringBuilder().append(task.getItemName()).append(task.getQuantity().stripTrailingZeros().toPlainString()).append(task.getUnitOfMeasure()).toString()); //默认使用“[产品]+[数量]+[单位]”格式。
                        data.setColor(task.getColorCode());
                        data.setDuration(task.getDuration());
                        data.setStart_date(task.getStartTime());
                        data.setParent("MO"+workorder.getWorkorderId().toString());//这里要设置为"MO+生产工单ID"的格式
                        data.setProduct(task.getItemName());
                        data.setQuantity(task.getQuantity());
                        data.setProcess(task.getProcessName());
                        data.setWorkstation(task.getWorkstationName());
                        data.setProgress(0f);
                        data.setType(UserConstants.GANTT_TASK_TYPE_TASK);
                        ganttData.add(data);
                    }
                }
            }
        }

        ganttTask.setData(ganttData);
        ganttTask.setLinks(ganttLinks);
        return AjaxResult.success(ganttTask);
    }

    /**
     * 查询指定日期之内的排产任务(拖动表格中的)
     */
    // @PreAuthorize("@ss.hasPermi('mes:pro:protask:list')")
    @GetMapping("/TaskList")
    public AjaxResult getTaskList(ProTask proTask){
        Date endDate = DateUtils.parseDate(proTask.getEndDate());
        Date startDate = DateUtils.parseDate(proTask.getStartDate());
        Map gmap = new HashMap<>();
        gmap.put("production_date_start",DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,startDate));
        gmap.put("production_date_end",DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,endDate));
        LGLeftJoinQueryWrapper<Object> lgLeftJoinQueryWrapper = new LGLeftJoinQueryWrapper<>(proTask,gmap);
        lgLeftJoinQueryWrapper.setDefaultDateFormat("yyyy-MM-dd HH:mm:ss");
        lgLeftJoinQueryWrapper.setSelectColumn("*" +
                ",( SELECT COUNT( 0 ) FROM pro_workorder WHERE batch_code = \"batchCode\" ) AS barrelage" +
                ",(SELECT string_agg(remark , ';') FROM wm_stock_will_out WHERE stock_type = 'pro_workorder' and stock_id = \"workorderId\"::VARCHAR) as willOutRemark " +
                "");
        List<JSONObject> list = wmStockOutService.lgListMap(lgLeftJoinQueryWrapper);

        QueryWrapper queryWrapper = new QueryWrapper<ProTask>();
        queryWrapper.between("production_date", startDate,endDate);
        queryWrapper.select("COUNT(0) as count,DATE_FORMAT(production_date,'%m月%d日') as dayStr");
        queryWrapper.groupBy("dayStr");
        List<Map> countList = proTaskService.listMaps(queryWrapper);

        QueryWrapper queryWrapper1 = new QueryWrapper<ProTaskChangeVersion>();
        queryWrapper1.select("version,DATE_FORMAT(mdate,'%m月%d日') as dayStr");
        queryWrapper1.between("mdate", startDate,endDate);
        List<Map> versionList = proTaskChangeVersionService.listMaps(queryWrapper1);

        Map map = new HashMap<>();
        map.put("count",countList);
        map.put("version",versionList);
        map.put("list",list);

        return AjaxResult.success(map);
    }

    /**
     * 查询当天的排产任务
     */
    @GetMapping("/todayList")
    public TableDataInfo timeOfTheDayProTask(ProTask proTask){
        startPage();
        List<ProTask> taskList = proTaskService.selectTimeOfTheDayProTask(proTask);
        return getDataTable(taskList);
    }



    /**
     * 新增生产任务
     */
    @PreAuthorize("@ss.hasPermi('mes:pro:protask:add')")
    @Log(title = "生产任务", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ProTask proTask)
    {

        //生产工单
        ProWorkorder order = proWorkorderService.selectProWorkorderByWorkorderId(proTask.getWorkorderId());
        proTask.setWorkorderCode(order.getWorkorderCode());
        proTask.setWorkorderName(order.getWorkorderName());
        proTask.setItemId(order.getProductId());
        proTask.setItemCode(order.getProductCode());
        proTask.setItemName(order.getProductName());
        proTask.setSpecification(order.getProductSpc());
        proTask.setUnitOfMeasure(order.getUnitOfMeasure());
        proTask.setViscosity(order.getViscosity());
        proTask.setClientId(order.getClientId());
        proTask.setClientCode(order.getClientCode());
        proTask.setClientName(order.getClientName());
        if (proTask.getQuantityNotIn() != null){
            proTask.setQuantityNotIn(proTask.getQuantity());
        }

        //工序信息
        ProProcess process = proProcessService.selectProProcessByProcessId(proTask.getProcessId());
        proTask.setProcessId(process.getProcessId());
        proTask.setProcessCode(process.getProcessCode());
        proTask.setProcessName(process.getProcessName());

        proTask.setIsGetMaterials("0");

        //自动生成任务编号和名称
        proTask.setTaskCode(order.getBatchCode());
        proTask.setTaskName(new StringBuilder().append(proTask.getItemName()).append(":").append(proTask.getViscosity()).toString());
        proTask.setBatchNo(proTaskService.selectPrintBatchNo());

        ;


        return toAjax(proTaskService.insertProTask(proTask));
    }

    /**
     * 新增生产任务
     */
    @PreAuthorize("@ss.hasPermi('mes:pro:protask:add')")
    @Log(title = "生产任务", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @Transactional
    public AjaxResult addProTask(@RequestBody ProTask proTask)
    {

        //生产工单
        ProWorkorder order = proWorkorderService.selectProWorkorderByWorkorderId(proTask.getWorkorderId());
        proTask.setWorkorderId(order.getWorkorderId());
        proTask.setWorkorderCode(order.getWorkorderCode());
        proTask.setWorkorderName(order.getWorkorderName());
        proTask.setItemId(order.getProductId());
        proTask.setItemCode(order.getProductCode());
        proTask.setItemName(order.getProductName());
        proTask.setSpecification(order.getProductSpc());
        proTask.setUnitOfMeasure(order.getUnitOfMeasure());
        proTask.setViscosity(order.getViscosity());
        proTask.setTaskCode(order.getBatchCode());
        proTask.setIsFinish("N");
        if(proTask.getRequestDate() == null){
            proTask.setRequestDate(order.getRequestDate());
        }

        proTask.setStatus("0");
        proTask.setIsGetMaterials("0");
        if (proTask.getQuantityNotIn() != null){
            proTask.setQuantityNotIn(proTask.getQuantity());
        }

        //判断如果是销售订单，则插入销售订单id
        if ("ORDER".equals(order.getOrderSource())){
            MesScalesOrderItem scalesOrderItem = new MesScalesOrderItem();
            scalesOrderItem.setScalesOrderItemCode(order.getSourceCode());
            QueryWrapper<MesScalesOrderItem> queryWrapper = new QueryWrapper<>(scalesOrderItem);
            scalesOrderItem = mesScalesOrderItemService.getOne(queryWrapper);
            if (scalesOrderItem != null){
                proTask.setScaleId(scalesOrderItem.getScalesOrderItemId());
            }
        }

        if(order.getClientId() != null){
            proTask.setClientId(order.getClientId());
            proTask.setClientCode(order.getClientCode());
            proTask.setClientName(order.getClientName());
        }

        //自动生成任务编号和名称
        proTask.setTaskCode(autoCodeUtil.genSerialCode(UserConstants.TASK_CODE,null));
        // proTask.setTaskName(new StringBuilder().append(proTask.getItemName()).append("【").append(proTask.getQuantity().toString()).append("】").append(proTask.getUnitOfMeasure()).toString());
        proTask.setTaskName(new StringBuilder().append(proTask.getItemName()).append(":").append(proTask.getViscosity()).toString());

        //转换日期格式
        proTask.setBatchNo(order.getBatchCode());
//        proTask.setProductionDate(DateUtils);
        if (order.getProrouteId() != null && order.getProrouteId() > 0){
            proTask.setRouteId(order.getProrouteId());
        }else {
            if (proTask.getRouteId() == null){
                proTask.setRouteId(0L);
            }
        }
        proTask.setTaskStatus("已排产");

        return toAjax( proTaskService.insertProTask(proTask));
    }

    private Date formatConversion(String str){
        Calendar cal = Calendar.getInstance();
        int year  = cal.get(Calendar.YEAR);

        String re = str.replace("月", "-").replace("日","");

        StringBuilder sb = new StringBuilder();
        sb.append(year).append("-").append(re);

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date parse = null;
        try {
            parse = format.parse(sb.toString());
            return parse;
        } catch (ParseException e) {
            return null;
            // e.printStackTrace();
        }

    }

    /**
     * 打印
     */
    @GetMapping("/jimureport/{taskId}")
    public JSONObject  printData(@PathVariable("taskId") Long taskId){
        ProTask task =  proTaskService.getById(taskId);
        // 查询产品粘度
        MdItem mdItem = mdItemService.getById(task.getItemId());

        RecLnspectionRecord recLnspectionRecord = new RecLnspectionRecord();
        recLnspectionRecord.setBatchNo(task.getBatchNo());
        QueryWrapper<RecLnspectionRecord> recordQueryWrapper = new QueryWrapper<>(recLnspectionRecord);
        recordQueryWrapper.orderByDesc("create_time");
        recordQueryWrapper.last(" limit 1");
        recLnspectionRecord = recLnspectionRecordService.getOne(recordQueryWrapper);


        ProTask taskOld =  new ProTask();
        taskOld.setWorkorderId(task.getWorkorderId());
        QueryWrapper<ProTask> oldproTaskQueryWrapper = new QueryWrapper<>(taskOld);
        oldproTaskQueryWrapper.le("production_date",task.getProductionDate());
        long count = proTaskService.count(oldproTaskQueryWrapper);

        ProWorkorder workorder = proWorkorderService.selectProWorkorderByWorkorderId(task.getWorkorderId());

        Map<String,String> map = new HashMap<>();
        map.put("row1",task.getTaskName());
        map.put("row2",task.getSpecification());
        map.put("row3",mdItem.getViscosity());
        map.put("row4", task.getBatchNo());
        if (recLnspectionRecord != null && recLnspectionRecord.getCreateTime() != null){
            map.put("row5",DateUtils.parseDateToStr("yyyy-MM-dd",recLnspectionRecord.getCreateTime()));
        }

        count = count+1;
        map.put("row6",String.valueOf(count));

        if (workorder != null && workorder.getQuantity() != null){
            double aa = workorder.getQuantity().doubleValue();
            aa = aa/500.0;
            map.put("row7", String.valueOf(aa));
        }else {
            map.put("row7", "1");
        }
        map.put("row8",DateUtils.parseDateToStr("yyyy-MM-dd HH:mm",new Date()) + "打印");
        ArrayList<Object> list = new ArrayList<>();
        list.add(map);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("data",list);
        return jsonObject;
    }


    /**
     * 修改生产任务
     */
    @PreAuthorize("@ss.hasPermi('mes:pro:protask:edit')")
    @Log(title = "生产任务", businessType = BusinessType.UPDATE)
    @PutMapping
    @Transactional
    public AjaxResult edit(@RequestBody ProTask proTask)
    {
        proTask.setTaskName(new StringBuilder().append(proTask.getItemName()).append("【").append(proTask.getQuantity().toString()).append("】").append(proTask.getUnitOfMeasure()).toString());
        //转换日期格式
        proTask.setProductionDate(this.formatConversion(proTask.getMonth()));
        return toAjax(proTaskService.updateProTask(proTask));
    }

    /**
     * 删除生产任务
     */
    @PreAuthorize("@ss.hasPermi('mes:pro:protask:remove')")
    @Log(title = "生产任务", businessType = BusinessType.DELETE)
	@DeleteMapping("/{taskIds}")
    @Transactional
    public AjaxResult remove(@PathVariable Long[] taskIds)
    {
        return toAjax(proTaskService.deleteProTaskByTaskIds(taskIds));
    }


    /**
     * 获取溶解半成品预估 界面配置
     */
    @GetMapping("/findDissolvedEstimateTableTitle")
    public AjaxResult findDissolvedEstimateTableTitle(String code,HttpServletRequest req){


        WebModel webModel = new WebModel();

        //配置查询条件
        List<QueryParam> queryParamList = new ArrayList<>();
        queryParamList.add(new QueryParam("开始时间","productionDate_start", QueryParam.ViewType.DateDay));
        queryParamList.add(new QueryParam("结束时间","productionDate_end", QueryParam.ViewType.DateDay));
        webModel.setQueryParams(queryParamList);

        //配置 table 头部标题
        Map map = req.getParameterMap();
        List<Object> dateList = initStartDateAndEndDate(map);
        Date fromDate = (Date) dateList.get(0);
        Date endDate = (Date) dateList.get(1);
        webModel.setColumns(findDissolvedEstimateColumns(fromDate,endDate));

        //配置界面权限
        PowerAuthentication powerAuthentication = new PowerAuthentication();
        powerAuthentication.setExcelOut(true,"/mes/pro/protask/excelTaskStockOut");
        webModel.setAuthentication(powerAuthentication);

        //标题
        webModel.setTitle("溶解半成品预估");

        return AjaxResult.success(webModel);
    }

    /**
     * 获取溶解半成品预估 界面配置
     * @param fromDate
     * @param endDate
     * @return
     */
    public List<TableColumn> findDissolvedEstimateColumns(Date fromDate,Date endDate){
        List<TableColumn> tableColumnList = new ArrayList<>();
        tableColumnList.add(new TableColumn("树脂型号","productName").setBackground("#eeee99").setFixed("left"));
        Integer count = DateUtils.differentDaysByMillisecond(endDate,fromDate);
        Integer countIndex = 1;
        for (int i = 0; i < count; i++) {
            Date fromItemDate = DateUtils.dateByAddSecond(fromDate, 24 * 3600 * i);
            String dataStr = DateUtils.parseDateToStr("MM月dd日", fromItemDate);
            String week = DateUtils.getWeek(fromItemDate);
            if (week.equals("星期日") || i == 0){
                tableColumnList.add(new TableColumn("当周用量",dataStr+countIndex).setBackground("#ee99ee"));
                countIndex++;
            }
            tableColumnList.add(new TableColumn(dataStr+"\n"+week,dataStr));
        }

        return  tableColumnList;
    }

    /**
     *  获取溶解半成品预估数据
     * @param req
     * @return
     */
    public List<Map> excelStockModelMapList(List<Object> dateList){
        //按统计分类，统计当天 用量
        List<Map> excelStockModelList = new ArrayList<>();
        Date fromDate = (Date) dateList.get(0);
        Date endDate = (Date) dateList.get(1);
        String startTime = (String) dateList.get(2);
        String endTime = (String) dateList.get(3);

        //获取 表格排产数据
        List<JSONObject> list1 = proTaskService.selectCountProTask(startTime,endTime);
        HashMap<String,JSONObject> proTaskMap = new HashMap<>();
        ArrayList<Long> itemIds = new ArrayList<>();

        //获取表格排产数据产品的物料组成
        List<MdProductStatisticsBom> bomList = null;

        //按统计分类，统计当天 用量
        Map<String,JSONObject> itemIdDayMap = new HashMap<>();

        //用于按 统计名称分类 BOM
        Map<String,ArrayList> bomProcessProductNameMap = new HashMap<>();

        if (list1 != null){
            for (int i = 0; i < list1.size(); i++) {
                // 根据key整理 产品
                JSONObject jsonObject = list1.get(i);
                Long itemId = jsonObject.getLong("item_id");
                proTaskMap.put(""+itemId,jsonObject);

                String aday = jsonObject.getString("aday");
                aday = aday.substring(5,10);
                aday = aday.replace("-","月") + "日";
                itemIdDayMap.put(itemId+":"+aday,jsonObject);

                // 统计产品ID
                itemIds.add(itemId);
            }

            if (itemIds != null && itemIds.size() > 0){
                //获取表格排产数据产品的物料组成
                QueryWrapper<MdProductStatisticsBom> mdProductStatisticsBomQueryWrapper = new QueryWrapper<>();
                mdProductStatisticsBomQueryWrapper.in("item_id",itemIds);
                bomList = productStatisticsBomService.list(mdProductStatisticsBomQueryWrapper);
                if (bomList != null){
                    for (MdProductStatisticsBom statisticsBom : bomList) {
                        ArrayList array =  bomProcessProductNameMap.get(statisticsBom.getStatisticsName());
                        if (array == null){
                            array = new ArrayList<>();
                            bomProcessProductNameMap.put(statisticsBom.getStatisticsName(),array);
                        }
                        array.add(statisticsBom);
                    }
                }
            }
        }

        if (bomList == null){
            return excelStockModelList;
        }

        Integer count = DateUtils.differentDaysByMillisecond(endDate,fromDate);

        for (String key: bomProcessProductNameMap.keySet()) {
            List<MdProductStatisticsBom> bomArr = bomProcessProductNameMap.get(key);
            String productName = key;
            //配料桶数 行
            Map item = new HashMap();
            item.put("productName",productName);

            float weekCount = 0;
            Integer countIndex = 1;
            Integer addDay = 0;

            for (int j = 0; j < count; j++) {
                Date fromItemDate = DateUtils.dateByAddSecond(fromDate, 24 * 3600 * j);
                String dataStr = DateUtils.parseDateToStr("MM月dd日", fromItemDate);
                Integer value = 0;
                if (item.get(dataStr) != null){
                    value = (Integer) item.get(dataStr);
                }

                for (MdProductStatisticsBom bom:bomArr) {
                    JSONObject protaskItem = itemIdDayMap.get(bom.getItemId()+":"+dataStr);
                    if (protaskItem != null){
                        float taskValue = protaskItem.getFloatValue("count");
                        int aa = (int) (taskValue*bom.getQuantity().floatValue());
                        value = value + Integer.valueOf(aa);
                    }
                }

                item.put(dataStr,value);
                weekCount += value;

                String week = DateUtils.getWeek(fromItemDate);
                if (week.equals("星期六")){
                    Date weekDate = DateUtils.dateByAddSecond(fromItemDate, -24 * 3600 * addDay);
                    String weekStr = DateUtils.parseDateToStr("MM月dd日", weekDate);
                    item.put(weekStr+countIndex,weekCount);
                    countIndex++;
                    weekCount = 0;
                    addDay = -1;
                }else {
                    Date weekDate = DateUtils.dateByAddSecond(fromItemDate, -24 * 3600 * addDay);
                    String weekStr = DateUtils.parseDateToStr("MM月dd日", weekDate);
                    item.put(weekStr+countIndex,weekCount);
                }
                addDay += 1;

            }
            excelStockModelList.add(item);
        }
        return excelStockModelList;
    }

    /**
     *  根据查询条件 ， 整理开始和结束日期
     * @param map
     * @return
     */
    public List<Object> initStartDateAndEndDate(Map map){
        String fromDataFromat  = "yyyy-MM-dd HH:mm:ss";
        String startTime = null;
        String endTime = null;

        if (map != null && map.containsKey("productionDate_start")){
            startTime =  (((String[])map.get("productionDate_start"))[0])+" 00:00:00";
        }else {
            startTime = DateUtils.parseDateToStr(fromDataFromat,new Date());
        }
        //整理日期，按周统计
        Date fromDate = DateUtils.dateTime(fromDataFromat,startTime);
        Integer aaaa1 = DateUtils.getWeekIndex(fromDate);
        fromDate = DateUtils.dateByAddSecond(fromDate,-24*3600*aaaa1);
        startTime = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,fromDate);

        if (map != null && map.containsKey("productionDate_end")){
            endTime = (((String[])map.get("productionDate_end"))[0])+" 00:00:00";
        }else {
            endTime = DateUtils.parseDateToStr(fromDataFromat,DateUtils.dateByAddSecond(fromDate,24*3600*31));
        }

        Date endDate = DateUtils.dateTime(fromDataFromat,endTime);
        Integer aaaa2 = DateUtils.getWeekIndex(endDate);
        if (aaaa2 != 0){
            endDate = DateUtils.dateByAddSecond(endDate,24*3600*(7-aaaa2));
        }
        endTime = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS,endDate);

        List<Object> list = new ArrayList<>();
        list.add(fromDate);
        list.add(endDate);
        list.add(startTime);
        list.add(endTime);
        return list;
    }


    /**
     * 导出未来5周 排产计划和库存
     */
//    @PreAuthorize("@ss.hasPermi('wm:wmItemSplit:excelTaskStock')")
    @Log(title = "排产计划和库存", businessType = BusinessType.EXPORT)
    @GetMapping("/taskStockEstimate")
    public Result taskStockEstimate(HttpServletResponse response, HttpServletRequest req)
    {

        APIResult apiLog = new APIResult("查询物料拆分列表",req,null);
        try {
            Map map = req.getParameterMap();
            List<Object> dateList = initStartDateAndEndDate(map);
            List<Map> mapList = excelStockModelMapList(dateList);
            //配置界面布局
            List<TableColumn> tableColumns = findDissolvedEstimateColumns((Date) dateList.get(0),(Date) dateList.get(1));
            return apiLog.ok(mapList,tableColumns);
        }catch (Exception e){
            return apiLog.error(e);
        }
    }


    @Autowired
    private IProItemNeedService proItemNeedService;


//    @PreAuthorize("@ss.hasPermi('pro:proItemNeed:export')")
    @Log(title = "客戶产品需求", businessType = BusinessType.EXPORT)
    @PostMapping("/excelTaskStockOut")
    public void export(HttpServletResponse response, ProItemNeed proItemNeed,HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("导出客戶产品需求列表",req,proItemNeed);
        try {
            Map map = req.getParameterMap();
            List<Object> dateList = initStartDateAndEndDate(map);
            List<Map> mapList = excelStockModelMapList(dateList);
            List<TableColumn> tableColumns = findDissolvedEstimateColumns((Date) dateList.get(0),(Date) dateList.get(1));

            List<ExcelTitle> excelTitleList = new ArrayList<>();
            Map weeMap = new HashMap<>();
            for (int i =0;i < tableColumns.size();i++){
                TableColumn column = tableColumns.get(i);
                ExcelTitle title = new ExcelTitle();
                String[] tList = column.getName().split("\n");
                title.setName(tList[0]);
                if (tList.length > 1){
                    weeMap.put(column.getProp(),tList[1]);
                }
                if (i == 0){
                    title.setFillForegroundColor(IndexedColors.YELLOW1);
                }
                if (title.getName().equals("当周用量")){
                    title.setFillForegroundColor(IndexedColors.BRIGHT_GREEN);
                }
                title.setDataName(column.getProp());
                title.setWidth(10);
                if (i == 0){
                    title.setDataType(String.class);
                }else {
                    title.setDataType(Long.TYPE);
                }
                excelTitleList.add(title);
            }
            mapList.add(0,weeMap);

            ExcelUtil2 util = new ExcelUtil2();
            ExcelRowModel excelRowModel = new ExcelRowModel();
            excelRowModel.setSheetName("溶解半成品预估");
            excelRowModel.setTitleList(excelTitleList);
            excelRowModel.setMapList(mapList);

            util.exportExcel(excelRowModel,response);
            apiLog.ok(null);
        }catch (Exception e){
            apiLog.error(e);
        }
    }


}
